<?php
	session_start();
	
	function getWords()
	{
		$words = array();
		if(!isset($_POST['search']) || $_POST['search'] == '')
			return $words;
		$words = explode(' ', $_POST['search']);
		return $words;
	}
	
	function buildQuery($words)
	{
		$_SESSION['search'] = 'SELECT Courses.* FROM Courses, SubCategories 
		WHERE Courses.SubCategory = SubCategories.Name ';
		
		foreach($words as $word)
		{
			$_SESSION['search'] = $_SESSION['search'] . 'AND (Courses.Name LIKE \'%' . $word . '%\' 
			OR SubCategories.Name LIKE \'%' . $word . '%\' OR SubCategories.CategoryName LIKE 
			\'%' . $word . '%\') ';
		}
		$_SESSION['search'] = $_SESSION['search'] . 'ORDER BY Courses.Name';
	}
	
	function buildAdvancedSearchQuery()
	{
		$query = 'SELECT * FROM Courses';
		$tables = '';
		$filters = '';
		
		if(isset($_POST['course']) && $_POST['course'] != '')
		{
			$filters = ' WHERE Courses.Name LIKE \'%' . $_POST['course'] . '%\'';
		}
		if(isset($_POST['professor']) && $_POST['professor'] != '')
		{
			$tables = ', ProfessorsCourses, Users';
			$temp = 'ProfessorsCourses.CourseId = Courses.Id AND ProfessorsCourses.ProfessorName = Users.Username ' .
				'AND (Users.Name LIKE \'%' . $_POST['professor'] . '%\' OR Users.Surname LIKE \'%' . $_POST['professor'] .
				'%\')';
			if($filters == '')
				$filters = ' WHERE ' . $temp;
			else
				$filters = $filters . ' AND ' . $temp;
		}
		if(isset($_POST['category']) && $_POST['category'] != '' && $_POST['category'] != 'all')
		{
			$temp = 'Courses.SubCategory = \'' . $_POST['category'] . '\'';
			if($filters == '')
				$filters = ' WHERE ' . $temp;
			else
				$filters = $filters . ' AND ' . $temp;
		}
		$query = $query . $tables . $filters;
		
		
		$_SESSION['search'] = $query;
	}
	
	if($_GET['action'] == 'simple_search')
	{
		$words = array();
		$words = getWords();
		buildQuery($words);
	}
	else if($_GET['action'] == 'advanced_search')
		buildAdvancedSearchQuery();
	
	header('Location: searched_courses.php');
?>
